package org.eiahe.hr.attendance.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.eiahe.hr.attendance.domain.bo.LeaveApplicationBo;
import org.eiahe.hr.attendance.domain.vo.LeaveApplicationVo;
import org.eiahe.hr.attendance.domain.vo.SyncLogVo;
import org.eiahe.hr.attendance.service.IDingTalkSyncService;
import org.eiahe.hr.attendance.service.ILeaveApplicationService;
import org.ehe.common.core.domain.R;
import org.ehe.common.core.validate.AddGroup;
import org.ehe.common.core.validate.EditGroup;
import org.ehe.common.excel.utils.ExcelUtil;
import org.ehe.common.log.annotation.Log;
import org.ehe.common.log.enums.BusinessType;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.ehe.common.core.BaseController;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

/**
 * 请假申请管理Controller
 *
 * @author zhangnn
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/attendance/leaveApplication")
public class LeaveApplicationController extends BaseController {

    private final ILeaveApplicationService leaveApplicationService;
    private final IDingTalkSyncService dingTalkSyncService;

    /**
     * 查询请假申请列表
     */
    @SaCheckPermission("attendance:leaveApplication:list")
    @GetMapping("/list")
    public TableDataInfo<LeaveApplicationVo> list(LeaveApplicationBo bo, PageQuery pageQuery) {
        return leaveApplicationService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出请假申请列表
     */
    @SaCheckPermission("attendance:leaveApplication:export")
    @Log(title = "请假申请", businessType = BusinessType.EXPORT, linkType = "leave")
    @PostMapping("/export")
    public void export(LeaveApplicationBo bo, HttpServletResponse response) {
        List<LeaveApplicationVo> list = leaveApplicationService.queryList(bo);
        ExcelUtil.exportExcel(list, "请假申请", LeaveApplicationVo.class, response);
    }

    /**
     * 获取请假申请详细信息
     *
     * @param applicationId 主键
     */
    @SaCheckPermission("attendance:leaveApplication:query")
    @GetMapping("/{applicationId}")
    public R<LeaveApplicationVo> getInfo(@NotNull(message = "主键不能为空") @PathVariable Long applicationId) {
        return R.ok(leaveApplicationService.queryById(applicationId));
    }

    /**
     * 新增请假申请
     */
    @SaCheckPermission("attendance:leaveApplication:add")
    @Log(title = "请假申请", businessType = BusinessType.INSERT, linkType = "leave")
    @PostMapping
    public R<Void> add(@Validated(AddGroup.class) @RequestBody LeaveApplicationBo bo) {
        return toAjax(leaveApplicationService.insertByBo(bo));
    }

    /**
     * 修改请假申请
     */
    @SaCheckPermission("attendance:leaveApplication:edit")
    @Log(title = "请假申请", businessType = BusinessType.UPDATE, linkType = "leave")
    @PutMapping
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody LeaveApplicationBo bo) {
        return toAjax(leaveApplicationService.updateByBo(bo));
    }

    /**
     * 删除请假申请
     *
     * @param applicationIds 主键串
     */
    @SaCheckPermission("attendance:leaveApplication:remove")
    @Log(title = "请假申请", businessType = BusinessType.DELETE, linkType = "leave")
    @DeleteMapping("/{applicationIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] applicationIds) {
        return toAjax(leaveApplicationService.deleteWithValidByIds(List.of(applicationIds)));
    }

    /**
     * 手动同步OA请假数据
     *
     * @param startDate 开始日期
     * @param endDate   结束日期
     */
    @SaCheckPermission("attendance:oaSync:manual")
    @Log(title = "手动同步OA数据", businessType = BusinessType.OTHER, linkType = "leave")
    @PostMapping("/manual")
    public R<SyncLogVo> manualSync(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        SyncLogVo syncLogVo = dingTalkSyncService.syncLeaveRecords(startDate, endDate, true);
        return R.ok("同步成功", syncLogVo);
    }

    /**
     * 一键同步昨天的OA请假数据
     */
    @SaCheckPermission("attendance:oaSync:manual")
    @Log(title = "同步昨天OA数据", businessType = BusinessType.OTHER, linkType = "leave")
    @PostMapping("/syncYesterday")
    public R<SyncLogVo> syncYesterday() {
        LocalDate yesterday = LocalDate.now().minusDays(1);
        SyncLogVo syncLogVo = dingTalkSyncService.syncLeaveRecords(yesterday, yesterday, true);
        return R.ok("同步成功", syncLogVo);
    }

    /**
     * 重试失败的同步记录
     *
     * @param logId 同步日志ID
     */
    @SaCheckPermission("attendance:oaSync:retry")
    @Log(title = "重试OA数据同步", businessType = BusinessType.OTHER, linkType = "leave")
    @PostMapping("/retry/{logId}")
    public R<Void> retrySync(@PathVariable Long logId) {
        dingTalkSyncService.retryLeaveSyncByLogId(logId);
        return R.ok();
    }

    /**
     * 审批通过
     *
     * @param applicationId 申请ID
     */
    @SaCheckPermission("attendance:leaveApplication:approve")
    @Log(title = "审批通过请假申请", businessType = BusinessType.UPDATE, linkType = "leave")
    @PostMapping("/approve/{applicationId}")
    public R<Void> approve(@NotNull(message = "申请ID不能为空") @PathVariable Long applicationId) {
        return toAjax(leaveApplicationService.approve(applicationId));
    }

    /**
     * 审批拒绝
     *
     * @param applicationId 申请ID
     * @param rejectReason  拒绝原因
     */
    @SaCheckPermission("attendance:leaveApplication:approve")
    @Log(title = "审批拒绝请假申请", businessType = BusinessType.UPDATE, linkType = "leave")
    @PostMapping("/reject/{applicationId}")
    public R<Void> reject(
            @NotNull(message = "申请ID不能为空") @PathVariable Long applicationId,
            @RequestParam(required = false) String rejectReason) {
        return toAjax(leaveApplicationService.reject(applicationId, rejectReason));
    }
}
